import {Message} from "@arco-design/web-vue";
import {useMapStore} from "./index";
import {saveTagsToStorage, saveToStorage} from "./storage";

// 标签管理功能
export const addNewTag = () => {
    const store = useMapStore();

    const newTag = {
        id: `tag_${Date.now()}`,
        name: "新标签",
        color: "#4dabf7",
        symbol: "N",
        order: store.addressTags.length,
    };
    store.addressTags.push(newTag);
    saveTagsToStorage();
};

export const updateTag = (tagId: string, updates: any) => {
    const store = useMapStore();

    const tag = store.addressTags.find(t => t.id === tagId);
    if (tag) {
        Object.assign(tag, updates);
        saveTagsToStorage();
    }
};

export const deleteTag = (tagId: string) => {
    const store = useMapStore();

    // 不能删除系统默认标签
    if (tagId === "unchecked" || tagId === "checked") {
        Message.warning("不能删除系统默认标签");
        return;
    }

    const tagIndex = store.addressTags.findIndex(t => t.id === tagId);
    if (tagIndex > -1) {
        // 将使用该标签的地址改为第一个标签
        const firstTag = store.addressTags.filter(t => t.id !== tagId).sort((a, b) => a.order - b.order)[0];
        store.addressList.forEach(address => {
            if (address.status === tagId) {
                address.status = firstTag ? firstTag.id : "unchecked";
            }
        });

        store.addressTags.splice(tagIndex, 1);
        saveTagsToStorage();
        saveToStorage();
        Message.success("标签删除成功");
    }
};

export const moveTag = (tagId: string, direction: "up" | "down") => {
    const store = useMapStore();

    const index = store.addressTags.findIndex(t => t.id === tagId);
    if (index === -1) return;

    const newIndex = direction === "up" ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= store.addressTags.length) return;

    // 交换位置
    const temp = store.addressTags[index];
    store.addressTags[index] = store.addressTags[newIndex];
    store.addressTags[newIndex] = temp;

    // 更新order
    store.addressTags.forEach((tag, i) => {
        tag.order = i;
    });

    saveTagsToStorage();
};
